package com.itheima.health.util;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sms.SmsClient;
import com.baidubce.services.sms.SmsClientConfiguration;
import com.baidubce.services.sms.model.SendMessageV3Request;
import com.baidubce.services.sms.model.SendMessageV3Response;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 张博源
 * @date 2024-04-16
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "bduyun.sms")
public class BduyunSms {
    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String templateId;
    private String signId;
    public SmsClient createClient() throws Exception {;
        SmsClientConfiguration config = new SmsClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(accessKeyId, accessKeySecret));
        config.setEndpoint(endpoint);
        return new SmsClient(config);
    }

    public String sendSms(String mobile) {
        try {
            //100000~999999   [100000,1000000)  [0, 900000)
            int code = 100000 + new Random().nextInt(900000);
            String smsCode = "{\"code\": \"" + code + "\"}";
            SendMessageV3Request request = new SendMessageV3Request();
            request.setMobile(mobile);
            request.setSignatureId(signId);
            request.setTemplate(templateId);
            Map<String, String> contentVar = new HashMap<>();
            contentVar.put("code", String.valueOf(code));
            contentVar.put("minute", "5");
            request.setContentVar(contentVar);
            SendMessageV3Response response = createClient().sendMessage(request);
            if ("1000".equals(response.getCode())) {
                return String.valueOf(code);
            } else {
                log.warn("发送短信失败，错误码：{}，错误消息：{}", response.getCode(),  response.getMessage());
                return null;
            }
        } catch (Exception e) {
            log.error("发送短信失败", e);
            return null;
        }
    }
}
